<?php
/*
 * edite in NetBeans of IDE at version 7.0.1.
 */
/**
 * 简单插件类。
 * 使用钩子形式的插件系统。
 *
 * @author Zuolong Wang
 */
class Plugin {
    private static $_pluginDir = 'Plug-in';
    private static $_instance = null;
    private static $_plugins = array();
    /**
     *插件扩展名
     * 2011-11-22 目前只支持 '.php'
     * @var static
     */
    private static $_ext = '.php';
    private function __construct() {
        //根目录
        defined('BIC_ROOT') || define('BIC_ROOT',substr(dirname(__FILE__),0,-16));
        define('DS',DIRECTORY_SEPARATOR);
        $this -> _pluginPath = BIC_ROOT . self :: $_pluginDir;
    }
    public static function init(){
        if (is_null(self :: $_instance)){
            self :: $_instance = new self();
        }
        return self :: $_instance;
    }
    public function add($hook,$pluginName){
        self :: $_plugins[$hook][] = $pluginName;
    }
    /**
     *加载对应hook上已注册的插件,并执行插件程序
     * @param type $hook
     * @return type 
     */
    public function trigger($hook){
        if (!isset(self :: $_plugins[$hook])) return;
        foreach (self :: $_plugins[$hook] as $plugin){
            //插件文件
            if (is_dir($this -> _pluginPath . $plugin)){
                $plugin_file = $this -> _pluginPath . $plugin . DS . $plugin . self :: $_ext;
            }else{
                $plugin_file = $this -> _pluginPath . DS . $plugin . self :: $_ext;
            }
            //合法性判断
            if (is_string($plugin) && preg_match("/^[\w\-\/]+/mi",$plugin) && is_file($plugin_file)){
                require $plugin_file;
                /**
                 * 将调用trigger()函数的第二个参数开始，都置为doAction()函数的所有参数
                 */
                $params =  array_slice(func_get_args(),1);
                call_user_func_array(array(new $plugin(),'doAction'),$params);
            }else{
                self :: log('插件文件不存在，或插件名称不合法 ：'.$plugin_file);
            }
        }
    }
    /**
     *插件日志记录
     * @param type $msg 
     */
    private static function log($msg){
        echo $msg;
    }
}

interface IPlugin{
    function doAction();
}
?>
